//
//  MainViewController.m
//  ZhihunewPaper
//
//  Created by 梅杰 on 16/7/5.
//  Copyright © 2016年 梅杰. All rights reserved.
//

#import "MainViewController.h"
#import "New.h"
#import "TopicImage.h"
#import "AppDelegate.h"
#import "ContentTableViewCell.h"
#import "hotNews.h"
#import "HotNewsVO.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "MainViewController.h"
#import "HttpsManager.h"
#import "cellNew.h"
#import "CellNewVO.h"
#import "detailNewViewController.h"
#import "TopNewVO.h"
#import "TopNew.h"

#define KImageHeight 200

@interface MainViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) UIScrollView *imageScrollView;
@property (weak, nonatomic) UIPageControl *pageControl;
@property (strong,nonatomic) NSArray *hotNews;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, weak) UITableView *homePageTableView;
@property (nonatomic, strong) NSArray *itemArray;
@property (nonatomic,strong) NSArray *topNewsArray;
@property (nonatomic,strong) NSDate *date;
@property (nonatomic,strong) NSMutableArray *beforeNewsArray;
@end

@implementation MainViewController
{
    NSArray *_itemArray;
    NSArray *_topNewsArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
//    [self initImageScrollView];
    self.title = @"今日热闻";
    
    //设置uinavigationBar 颜色
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:20/255.0 green:155/255.0 blue:213/255.0 alpha:1.0]];
    [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0.0];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self initHomePageTableView];
    //添加弹出左视图的按钮
//    self.navigationController.navigationItem.leftBarButtonItem = [self getToggLeftVCButton];
//    self.navigationController.navigationBar.alpha = 0;
    
//    self.navigationController.navigationBar
    self.navigationItem.leftBarButtonItem = [self getToggLeftVCButton];
//    [self.navigationController setHidesBarsOnTap:YES];
    

}
//- (BOOL)prefersStatusBarHidden{
//    return YES;
//}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getNews];
    [self getTimer];
//    [self.navigationController setNavigationBarHidden:NO];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    [self.navigationController setNavigationBarHidden:NO];
    [self.timer invalidate];
    self.timer = nil;
}
- (NSArray *)hotNews{
    if (!_hotNews) {
//        _hotNews = [HotNewsVO hotNewsArray];
//        _hotNews = [_hotNews valueForKeyPath:@"title"];
//        [self.homePageTableView reloadData];
    }
    return _hotNews;
}

- (void)setItemArray:(NSArray *)itemArray{
    _itemArray = itemArray;
    
    if (_itemArray) {
//        NSArray *newsIDArray = [itemArray valueForKeyPath:@"id"];
//        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//        appDelegate.newsIDArray = newsIDArray;
        [self.homePageTableView reloadData];
    }
}

- (NSArray *)itemArray{
    
    if (_itemArray == nil) {
        [self getNews];
    }
    return _itemArray;
}
- (NSArray *) topNewsArray{
    if (_topNewsArray == nil) {
        [self getNews];
    }
    return _topNewsArray;
}
- (NSArray *)beforeNewsArray{
    if (_beforeNewsArray == nil) {
        _beforeNewsArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _beforeNewsArray;
}
//进行网络请求，得到今天的topnews和cellNews
- (void) getNews{
    
    NSString *url = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"interface.plist" ofType:nil]][@"lastNews"];
    NSDictionary *parm = nil;
    
//    NSMutableDictionary *newsDict = [NSMutableDictionary dictionaryWithCapacity:0];
    
    [HttpsManager getUrlDataWithUrl:url Param:parm Success:^(NSDictionary * _Nonnull dict, Boolean flag) {
        //            NSLog(@"itemArray %@",dict);
        if (flag) {
            NSArray *lastNewsArray = [CellNewVO cellNewsArray:dict];
            if (lastNewsArray.count > 0) {
//                [newsDict setObject:lastNewsArray forKey:@"cellNews"];
                self.itemArray = lastNewsArray;
            }
            NSArray *topNewsArray = [TopNewVO topNewsArray:dict];
            if (topNewsArray.count > 0) {
//                [newsDict setObject:topNewsArray forKey:@"topNews"];
                self.topNewsArray = topNewsArray;
            }
            [self.homePageTableView.mj_header endRefreshing];
        }
        
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
    }];

}
//得到之前的新闻
- (void) getPassNews{
    NSString *baseUrl = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"interface.plist" ofType:nil]][@"before"];
    NSString *url = [NSString stringWithFormat:@"%@/%@",baseUrl,[self getDateNsstring:[self getNextDate]]];
    NSDictionary *parm = nil;
    
    //    NSMutableDictionary *newsDict = [NSMutableDictionary dictionaryWithCapacity:0];
    
    [HttpsManager getUrlDataWithUrl:url Param:parm Success:^(NSDictionary * _Nonnull dict, Boolean flag) {
        //            NSLog(@"itemArray %@",dict);
        if (flag) {
            NSArray *lastNewsArray = [CellNewVO cellNewsArray:dict];
            if (lastNewsArray.count > 0) {
                //                [newsDict setObject:lastNewsArray forKey:@"cellNews"];
                [self.beforeNewsArray addObject:lastNewsArray];
            }
            
        }
        
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
    }];

}
//弹出左视图
- (UIBarButtonItem *) getToggLeftVCButton {
    UIBarButtonItem *togLVCBu = [[UIBarButtonItem alloc] init];
//    togLVCBu.frame = CGRectMake(0, 10, 50, 50);
    
//    togLVCBu.imageView.image = [UIImage imageNamed:@"img_toggleButton.png"];
    UIImage *image = [UIImage imageNamed:@"iOS6_Home_Icon_Menu_G"];
    togLVCBu.image = image;
//    [togLVCBu setImage:image forState:UIControlStateNormal];
//    [togLVCBu setImage:[UIImage imageNamed:@"iOS6_Home_Icon_Menu_G_Highlight"] forState:UIControlStateNormal];
//    togLVCBu.adjustsImageWhenHighlighted = YES;
//    [togLVCBu addTarget:self action:@selector(toggleLeftVC:) forControlEvents:UIControlEventTouchUpInside];
    togLVCBu.target = self;
    togLVCBu.action = @selector(toggleLeftVC:);
//    togLVCBu.backgroundColor = [UIColor redColor];
    return togLVCBu;
}
//弹出左视图
- (void)toggleLeftVC:(UIButton *)sender {
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate.mmDrawer toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}
//创建主页tableview
- (void) initHomePageTableView{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getNews];
    }];;
    self.homePageTableView = tableView;
    [self.view addSubview:tableView];
    tableView.backgroundColor = [UIColor whiteColor];
    
    __weak typeof(self) __wakeme = self;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(__wakeme.view);
        make.leading.equalTo(__wakeme.view);
        make.trailing.equalTo(__wakeme.view);
        make.bottom.equalTo(__wakeme.view).offset(-5);
    }];
//    NSLog(@"homePageTable 的尺寸%@", NSStringFromCGRect(tableView.frame));
}
#pragma mark tableview的代理方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0){
    return [self getImageScrollView];
    }
    else{
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 50)];
        label.backgroundColor = [UIColor colorWithRed:20/255.0 green:155/255.0 blue:213/255.0 alpha:1.0];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = [self getTableHeadViewLblText];
        return label;
    }
//    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return KImageHeight;
    }else{
        return 50;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return (1 + self.beforeNewsArray.count);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.itemArray.count;
    }else{
        return ((NSArray *)self.beforeNewsArray[section - 1]).count;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *newsID = ((cellNew *)self.itemArray[indexPath.row]).id;
    appDelegate.newsID = newsID;
    appDelegate.newsIDArray = [self.itemArray valueForKey:@"id"];
    detailNewViewController *aNewVc = [[detailNewViewController alloc] init];
    self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:aNewVc animated:YES completion:nil];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    CGFloat height = 0;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        cellNew *aNew = ((cellNew*)self.itemArray[indexPath.row]);
//        height = [NSURL URLWithString:aNew.images];
//    });
//    return [self cellHeightForTitle:aNew.title] + 30;
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ident = @"identifity";
    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (!cell) {
        cell = [[ContentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
        cell.contentLabel.font = [UIFont systemFontOfSize:16];
    }
    cellNew *aNew = ((cellNew*)self.itemArray[indexPath.row]);
    cell.contentLabel.text = aNew.title;
//    [cell.contentImageView sd_setImageWithURL:[NSURL URLWithString:aNew.thumbnail] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        NSLog(@"图片加载完成");
//    }];
    [cell.contentImageView sd_setImageWithURL:[NSURL URLWithString:aNew.images] placeholderImage:[UIImage imageNamed:@"loadImageFailed"]];
    
    return cell;
}

//得到每行的高度
- (CGFloat)cellHeightForTitle : (NSString *)title{
//     NSLog(@"homePageTable 的尺寸%@", NSStringFromCGRect(self.homePageTableView.frame));
    CGFloat width = (self.view.frame.size.width - 10)*0.75;
    UIFont *font = [UIFont systemFontOfSize:16];
    NSDictionary *dict = @{NSFontAttributeName : font};
    CGSize size = [title boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
//    NSLog(@"宽度%f",width);
//    NSLog(@"宽度%f",size.width);
//    NSLog(@"高度%f",size.height);
    return size.height;
}
- (CGFloat)cellHeightForImage : (UIImage *)image{
    //     NSLog(@"homePageTable 的尺寸%@", NSStringFromCGRect(self.homePageTableView.frame));
    return image.size.height;
}
#pragma mark 生成计时器
//
- (void) getTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:6.0 target:self selector:@selector(scrollImage) userInfo:nil repeats:YES];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:self.timer forMode:NSRunLoopCommonModes];
}
#pragma mark 创建轮播器视图
//
- (UIView *) getImageScrollView{
    
    UIView *tableHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenWidth)];
    [self.view addSubview:tableHeadView];
    
//    CGFloat imageHeight = KImageHeight;
    //建一个UIscrollview
    UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, KImageHeight - KScreenWidth, KScreenWidth, KScreenWidth)];
    scrollview.contentSize = CGSizeMake(5*KScreenWidth, 0);
    scrollview.showsVerticalScrollIndicator = NO;
    scrollview.showsHorizontalScrollIndicator = NO;
//    scrollview.backgroundColor = [UIColor yellowColor];
    scrollview.pagingEnabled = YES;
    scrollview.delegate = self;
    [tableHeadView addSubview:scrollview];
    self.imageScrollView = scrollview;
    
//    UIRefreshControl *control=[[UIRefreshControl alloc]init];
//    [control addTarget:self action:@selector(getNews) forControlEvents:UIControlEventValueChanged];
//    [scrollview addSubview:control];
//    control.backgroundColor = [UIColor redColor];
    __weak typeof(UIScrollView *) __wakeScrollView = scrollview;
//    [control mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.center.equalTo(__wakeScrollView);
//        make.size.mas_equalTo(CGSizeMake(20, 20));
//    }];
    //开启页面控制器
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.tintColor = [UIColor clearColor];
    pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    pageControl.numberOfPages = 5;
    pageControl.hidesForSinglePage = YES;
    pageControl.currentPage = 0;
    self.pageControl = pageControl;
    [tableHeadView addSubview:pageControl];
//    __weak typeof(self) __wakeme = self;

    [pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(KScreenWidth/2);
        make.bottom.equalTo(__wakeScrollView).offset(-5);
        make.centerX.equalTo(__wakeScrollView);
    }];
    
    //创建计时器轮播scrollview

    for (int i = 0; i < 5; i++) {
        CGFloat topicImageX = i * KScreenWidth;
//        NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"img_%02d",i+1] ofType:@"png"];
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d",i+1]];
        TopicImage *aTopicImage = nil;
        if (self.topNewsArray) {
            aTopicImage = [[TopicImage alloc] initWithFrame:CGRectMake(topicImageX, 0, KScreenWidth, KScreenWidth) Title:((TopNew*)self.topNewsArray[i]).title];
            [aTopicImage.ImageView sd_setImageWithURL:[NSURL URLWithString:((TopNew*)self.topNewsArray[i]).image] placeholderImage:[UIImage imageNamed:@"loadImageFailed"]];
        }else{
            aTopicImage = [[TopicImage alloc] initWithFrame:CGRectMake(topicImageX, 0, KScreenWidth, KScreenWidth) Title:nil];
        }
//        aTopicImage.backgroundColor = [UIColor blueColor];
        [scrollview addSubview:aTopicImage];
        
        UITapGestureRecognizer *touchUpInside = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageScrollviewClicked:)];
        
        [scrollview addGestureRecognizer:touchUpInside];
    }
//    New *aNew = [[New alloc] init];
//    aNew = nil;
    
    return tableHeadView;
}
#pragma mark 滚动图片点击方法
- (void) imageScrollviewClicked:(UITapGestureRecognizer *)gesture{
    NSInteger page = self.pageControl.currentPage;
    NSString *newID = ((TopNew *)self.topNewsArray[page]).id;
    AppDelegate* appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.newsID = newID;
    appDelegate.newsIDArray = [self.topNewsArray valueForKey:@"id"];
    detailNewViewController *detailVC = [[detailNewViewController alloc] init];
    
    [self presentViewController:detailVC animated:YES completion:nil];
}
#pragma mark 图片滚动方法
//自动滚动图片
- (void)scrollImage{
    NSInteger page = self.pageControl.currentPage;
    
    if (page == self.pageControl.numberOfPages - 1) {
        page = 0;
    }else{
        page++;
    }
    static int index = 0;
    NSLog(@"滚动 %d",index++);
    
    CGFloat offSetx = page * self.imageScrollView.frame.size.width;
    
    [self.imageScrollView setContentOffset:CGPointMake(offSetx, 0) animated:YES];
}
#pragma mark scrollview的代理方法
//UIScrollView的滚动方法
- (void) scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if ([scrollView isEqual:self.imageScrollView]) {
        
    CGFloat offSetx = scrollView.contentOffset.x;
    offSetx = offSetx + (scrollView.frame.size.width * 0.5);
    
    int page = offSetx / scrollView.frame.size.width;
    self.pageControl.currentPage = page;
        
    }
    
    if ([scrollView isEqual:self.homePageTableView]) {
        CGPoint offset = scrollView.contentOffset;
        if (offset.y < -(KScreenWidth - KImageHeight) ) {
            scrollView.contentOffset = CGPointMake(0, KImageHeight - KScreenWidth);
        }
        
        CGFloat alpha = offset.y/KImageHeight;
        [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:alpha];
        NSLog(@"透明度%f",alpha);
    }
    
    
}

//UIScrollView即将开始拖拽
- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.homePageTableView]){
        [self.timer invalidate];
        self.timer = nil;
    }

    
}
//UIScrollView结束拖拽
- (void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    // 重新启动一个计时器
    if ([scrollView isEqual:self.homePageTableView]) {
        [self getTimer];
        
        CGPoint offset = scrollView.contentOffset;
        if (offset.y < -(KScreenWidth - KImageHeight) + 50) {
//            [self getNews];
            [self.homePageTableView bringSubviewToFront:self.homePageTableView.mj_header];
            [self.homePageTableView.mj_header beginRefreshing];
        }
    }
   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 得到昨天的日期字符串
- (NSString *) getDateNsstring : (NSDate *) date{
 
//    NSDate *nextDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:self.date];
//    self.date = lastDay;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMdd"];
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}
- (NSDate *)getNextDate{
    NSDate *nextDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:self.date];
    self.date = nextDay;
    return nextDay;
}
- (NSString *) getTableHeadViewLblText {
    NSString *month = [[self getDateNsstring : self.date] substringToIndex:2];
    NSString *day = [[self getDateNsstring : self.date] substringFromIndex:2];
    NSString *weekday = [self weekdayStringFromDate:self.date];
    NSString *retString = [NSString stringWithFormat:@"%@月%@日 %@",month,day,weekday];
    return retString;
}
- (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}
- (NSDate *)date{
    if (!_date) {
        _date = [NSDate date];
    }
    return _date;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
